//Author : Ravi

package com.redribbon.droidnoise;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

import android.util.Log;


class ReadMedia
{
	Vector<SongContainer> playlist;	// Access to this vector would need to be mutexed if activity needs to write to it multiple times
	int index; 					// Index into the playlist for the song currently being played
	MessageParser msgParser;
	NoiseServer noiseNet;
	boolean toStop;
	
	ReadMedia()
	{
		playlist = new Vector<SongContainer>();
		noiseNet = new NoiseServer(NoiseConstants.wifiman);
		msgParser = new MessageParser(noiseNet);
		toStop = false;
	}
	
	public void pushFiles(ArrayList<SongContainer> mediaList) 	//Josh is gonna call this
	{		
		playlist.addAll(mediaList);
		try
		{
			startSendingData();
		}
		catch(IOException ioe)
		{ }
	}
	
	void stopEverything()
	{
		toStop = true;
		noiseNet.resetSocket();
	}
	
	private void startSendingData() throws IOException
	{
		double avgByteRate;
		long playtimePerBuffer, countBytes, start, stop;
		for(int i = 0; i < playlist.size(); ++i)						// For each file
		{
			countBytes = 0;
			avgByteRate = playlist.elementAt(i).size / playlist.elementAt(i).duration;
			playtimePerBuffer = (long) (NoiseConstants.BUFFERSIZE / avgByteRate);
			msgParser.changeMetaData(playlist.elementAt(i));
			
			File fs = new File("/sdcard/15 Alive.mp3");
			long fileSize = fs.length();
			Log.i("RAVI INFO", "Length "+fileSize);
			FileInputStream fileStream = new FileInputStream("/sdcard/15 Alive.mp3");
			while(countBytes < fileSize)
	//			while(playlist.elementAt(i).data.available() > 0)// && toStop == false)
				{
					start = java.lang.System.currentTimeMillis();
					// msgParser.sendMediaData(playlist.elementAt(i).data, NoiseConstants.BUFFERSIZE, countBytes);
					msgParser.sendMediaData(fileStream, NoiseConstants.BUFFERSIZE, countBytes);
					countBytes += NoiseConstants.BUFFERSIZE;
					stop = java.lang.System.currentTimeMillis();					
	//				try
	//				{
	//					Thread.sleep(500); // DO NOT SLEEP HERE IF YOU DON'T WANT TO THROTTLE
	//				}
	//				catch(InterruptedException ioe)
	//				{ Log.i("RAVI INFO", "Interrupted while sleeping"); }
				}
				
			
			
			
		}				
	}
}
